﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.DTO.Org;
using BaseAuthRole.IService;
using BaseAuthRole.Service;
using BaseAuthRole.Web.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RS.BaseModel.Common;
using RS.Tool.Base;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace BaseAuthRole.Web.Api.Client
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserForClientController : ControllerBase
    {

        private IUserService _userService;
        public UserForClientController(IUserService userService)
        {
            this._userService = userService;
        }


        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult UpdateFeishuId([FromQuery] UpdateFeishuIdInput input)
        {
            return Ok(this._userService.UpdateFeishuId(input));
        }


        //[ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult CancelToken([FromQuery] CancelAuthTokenInput input)
        {

            return Ok(this._userService.CancelAuthToken(input));

        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetUserInfoList([FromQuery] GetUserInfoListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("user")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            var result = this._userService.GetUserInfoList(input);
            //根据供应商处理手机号，身份证号
            foreach (var data in result.Result.Data)
            {
                data.IdCardNo = "";
                if (!(data.EmployeeType == "7" || data.EmployeeType == "98" || data.EmployeeType == "99" || data.EmployeeType == "101"))
                {
                    data.Phone = "";
                }
                //供应商脱敏处理
                else
                {
                    if (!string.IsNullOrEmpty(data.Phone))
                    {
                        data.Phone = string.Format("{0," + data.Phone.Length + "}", " ").Replace(" ", "*");
                    }

                    //如果账号为手机号，也进行脱敏处理
                    long num;
                    if (long.TryParse(data.LoginName, out num))
                    {
                        data.LoginName = string.Format("{0," + data.LoginName.Length + "}", " ").Replace(" ", "*");
                    }
                }
            }

            return Ok(result);
        }

        /// <summary>
        /// 获取用户角色列表
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetUserRoleList([FromQuery] GetUserRoleListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("user")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            CommonResult<List<GetUserRoleListClientOut>> result = new CommonResult<List<GetUserRoleListClientOut>>();
            result.Result = new List<GetUserRoleListClientOut>();

            var user_role = _userService.GetCJWUserRoleRelation(input.UserId);
            long count = 0;
            var roles = _userService.GetRoles(1, 100000, "", " \"CreateTime\"", out count, null);

            foreach (var role in roles)
            {
                var getUserRoleListClientOut = new GetUserRoleListClientOut()
                {
                    Id = role.Id,
                    Name = role.Name,
                    Checked = user_role.Any(p => p.Id == role.Id)
                };
                result.Result.Add(getUserRoleListClientOut);
            }

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;

            return Ok(result);
        }

        /// <summary>
        /// 更新用户角色列表
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult UpdateUserRoleList([FromBody] UpdateUserRoleListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("user")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            CommonResult result = new CommonResult();

            var info = this._userService.GetUIUser(input.UserId);

            if (info == null)
            {
                result.IsError = true;
                result.Message = "用户不存在";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;

                return Ok(result);
            }

            if (input.RoleIds == null)
            {
                input.RoleIds = new List<string>();
            }

            this._userService.UpdateUserRole(info, input.RoleIds);

            result.IsError = false;
            result.Message = "更新成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;

            return Ok(result);
        }

        /// <summary>
        /// 获取组织树列表
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetOrgTreeList([FromQuery] GetOrgTreeListInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("user")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.SystemError
                });
            }

            return Ok(this._userService.GetOrgTreeList());
        }
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetOrgAuthInfo([FromQuery] GetOrgAuthInfoInput input)
        {
            var result = new CommonResult();
            var objects = new List<string>();
            var orgList = this._userService.GetOrgList().Result;
            var orgTreeOutPuts = new List<ActionTree>();
            BuildOrgTree(orgList, "0", objects, orgTreeOutPuts, input.IsValid);
            result.IsError = false;
            result.Result = orgTreeOutPuts;
            return Ok(result);

        }
        /// <summary>
        /// 构造组织树结构
        /// </summary>
        /// <param name="infos">组织信息列表</param>
        /// <param name="parentId">父节点Id</param>
        /// <param name="objects">被选中节点</param>
        /// <param name="orgTreeOutPuts">组织树输出对象</param>
        /// <returns></returns>
        [NonAction]
        public static void BuildOrgTree(List<Organization> infos, string? parentId, List<string> objects, List<ActionTree> orgTreeOutPuts, bool? isValid)
        {
            var orgs = infos.Where(p => p.ParentId == parentId).ToList();
            foreach (var org in orgs)
            {
                if (isValid == false || org.State == DTO.Org.Enum.EnumOrgState.valid)
                {
                    orgTreeOutPuts.Add(new ActionTree
                    {
                        id = org.Id,
                        parent = org.ParentId == "0" ? "#" : org.ParentId,
                        text = org.OrgName,
                        state = new ActionTreeState
                        {
                            selected = objects.Any(m => m == org.Id)
                        }
                    });
                    BuildOrgTree(infos, org.Id, objects, orgTreeOutPuts, isValid);
                }
            }
        }
        /// <summary>
        /// 获取组织树用户列表
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetOrgUserTreeList([FromQuery] GetOrgUserTreeListInput input)
        {
            return Ok(this._userService.GetOrgUserTreeOutList(input));
        }

        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult AddUserVisitRecord([FromQuery] BaseUserInputModel input)
        {
            var ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Connection.RemoteIpAddress == null ? "" : HttpContext.Connection.RemoteIpAddress.ToString();
            }
            ip = ip.Split(":").Last();
            return Ok(this._userService.AddUserVisitRecord(ip, input.Uid));
        }
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult AddUserModuleVisitRecord([FromQuery] AddUserModuleVisitRecordInput input)
        {
            var ip = HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();
            if (string.IsNullOrEmpty(ip))
            {
                ip = HttpContext.Connection.RemoteIpAddress == null ? "" : HttpContext.Connection.RemoteIpAddress.ToString();
            }
            ip = ip.Split(":").Last();
            return Ok(this._userService.AddUserModuleVisitRecord(ip, input.Module, input.Uid));
        }
    }
}
